//
//  ViewController.m
//  CoreBluetooth_BLE_protocol
//
//  Created by wujia121 on 17/8/27.
//  Copyright © 2017年 steven. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface ViewController ()<CBPeripheralManagerDelegate>

@property (strong, nonatomic) CBPeripheralManager *peripManager;
@property (strong, nonatomic) CBMutableCharacteristic *character;

@end

@implementation ViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //创建蓝牙外设管理者
    self.peripManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:dispatch_get_main_queue()];

    //判断iphone蓝牙状态
    switch ([CBPeripheralManager authorizationStatus]) {
        case CBPeripheralManagerAuthorizationStatusNotDetermined:
        {
            NSLog(@"用户还未决定APP能否使用蓝牙，赶紧调用下蓝牙框架，让系统弹框，让用户进行选择");
            [self.peripManager startAdvertising:nil];
            break;
        }
        case CBPeripheralManagerAuthorizationStatusAuthorized:
        {
            NSLog(@"App已被授权使用蓝牙");
            break;
        }
        case CBPeripheralManagerAuthorizationStatusRestricted:
        {
            NSLog(@"设备被家长远程控制，你无法操作");

            break;
        }
        case CBPeripheralManagerAuthorizationStatusDenied:
        {
            NSLog(@"App被禁用蓝牙");
            break;
        }
    }
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
  
}

#pragma mark ============ CBPeripheralManagerDelegate ==============
/*
 typedef NS_ENUM(NSInteger, CBManagerState) {
	CBManagerStateUnknown = 0,
	CBManagerStateResetting,
	CBManagerStateUnsupported,
	CBManagerStateUnauthorized,
	CBManagerStatePoweredOff,
	CBManagerStatePoweredOn,
 } NS_ENUM_AVAILABLE(NA, 10_0);
 */
static NSString * const UUID_Character = @"CDD1";
static NSString * const UUID_Server = @"CDD2";

/*当创建CBPeripheralManager的时候，会回调判断蓝牙状态的方法*/
- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheralManager {
    
    NSLog(@"peripheralManager代理方法被调用State:%zd",peripheralManager.state);
    if (peripheralManager.state == CBManagerStatePoweredOn) {
        
        // 创建Service（服务）和Characteristics（特征）
        CBMutableCharacteristic *character = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:UUID_Character] properties:CBCharacteristicPropertyRead|CBCharacteristicPropertyWrite|CBCharacteristicPropertyNotify value:nil permissions:CBAttributePermissionsReadable|CBAttributePermissionsWriteable];
        self.character = character;
        
        CBUUID *serverUUID = [CBUUID UUIDWithString:UUID_Server];
        CBMutableService *service = [[CBMutableService alloc] initWithType:serverUUID primary:YES];
        service.characteristics = @[character];
        
        [self.peripManager addService:service];
        
        // 根据服务的UUID开始广播
        [self.peripManager startAdvertising:@{CBAdvertisementDataServiceUUIDsKey : serverUUID }];
    }

}

/*中心设备订阅成功的时候回调*/
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didSubscribeToCharacteristic:(CBCharacteristic *)characteristic {
    NSLog(@"中心设备订阅成功:%@ 特征：%@",central,characteristic);

}

/*中心设备取消订阅的时候回调*/
- (void)peripheralManager:(CBPeripheralManager *)peripheral central:(CBCentral *)central didUnsubscribeFromCharacteristic:(CBCharacteristic *)characteristic {
    NSLog(@"中心设备取消订阅:%@ 特征：%@",central,characteristic);
}

/** 当中心设备请求读取这个外设的数据的时候会回调这个方法，此时外设应该写入数据 */
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request {
    NSString *msgTobeSent = @"xxxx23134876";
    request.value = [msgTobeSent dataUsingEncoding:NSUTF8StringEncoding];
    //发送request
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
}

/** 当中心设备请求向这个外设写入数据的时候会调用下面这个方法，此时外设应该读取数据 */
- (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveWriteRequests:(NSArray<CBATTRequest *> *)requests {
    CBATTRequest *req = requests.lastObject;
    NSData *data = req.value;
    NSString *msg = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"从中心设备读取到数据:%@",msg);
}


//主动给中心设备发送数据的方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSString *msg = @"abcd1234";
    BOOL res = [self.peripManager updateValue:[msg dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:self.character onSubscribedCentrals:nil];
    NSLog(@"外设->中心发送消息:%@ 结果：%d",msg, res);
}


@end
